package com.fk.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fk.reggie.common.R;
import com.fk.reggie.domain.Category;
import com.fk.reggie.domain.Dish;
import com.fk.reggie.domain.DishFlavor;
import com.fk.reggie.dto.DishDto;
import com.fk.reggie.service.CategoryService;
import com.fk.reggie.service.DishFlavorService;
import com.fk.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping
    public R<String> add(@RequestBody DishDto dishDto) {
        log.info("map中的数据为：{}", dishDto);
        dishService.saveWithFlavor(dishDto);
        //方案一  redis全清除
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
//        //方案二  添加只需要清除当前菜品分类的缓存  因为添加不会造成其他的菜品分类改变
//        redisTemplate.delete("dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus());
        return R.success("添加成功");
    }

    //请求 URL: http://localhost:8080/dish/page?page=1&pageSize=10&name=111
    @GetMapping("/page")
    public R<Page<DishDto>> page(Integer page, Integer pageSize, String name) {
        Page<Dish> dishPage = new Page<>(page, pageSize);

        Page<DishDto> dishDtoPage = new Page<>();

        //构造条件查询器
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.like(StringUtils.isNotBlank(name), Dish::getName, name)
                .orderByDesc(Dish::getUpdateTime);

        //分页查询
        dishService.page(dishPage, dishLambdaQueryWrapper);


        //拷贝分页信息 不拷贝数据  因为数据中不包含菜品分类的名称
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");

        List<Dish> dishList = dishPage.getRecords();

        List<DishDto> dishDtoList = dishList.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            //copy dish数据到dishDto中
            BeanUtils.copyProperties(dish, dishDto);
            Category category = categoryService.getById(dish.getCategoryId());
            //将菜品分类名称保存
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());
        //将分页数据保存到dishDto中
        dishDtoPage.setRecords(dishDtoList);
        return R.success(dishDtoPage);
    }

    //请求 URL: http://localhost:8080/dish/1397849739276890114
    //请求方法: GET
    @GetMapping("/{id}")
    public R<DishDto> getDishById(@PathVariable("id") Long id) {
        DishDto dishDto = dishService.getDishWithFavor(id);
        return R.success(dishDto);
    }

    //请求 URL: http://localhost:8080/dish
    //请求方法: PUT
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateDishWithFavor(dishDto);
        //修改成功建议直接清空redis缓存  因为 菜品可以修改分类  若只是清除一个缓存就会出现问题
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("修改成功");
    }

    //请求 URL: http://localhost:8080/dish/status/0?ids=1397849739276890114
    //请求方法: POST
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable("status") Integer status, @RequestParam("ids") List<Long> ids) {
        dishService.updateStatusByBatch(status, ids);
        //修改状态  建议直接请redis缓存  如果一个一个查写起来太费事了
        //方案一  redis全清除
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        //方案二  只清除被停售的dish缓存  建议放在service
//        Dish dish;
//        for (Long id : ids) {
//            dish = dishService.getById(id);
//            //只清除状态被修改的   可能会造成重复清除  因为可以修改多个菜品的状态 而多个菜品可能同属一个分类下
//            redisTemplate.delete("dish_"+dish.getCategoryId()+"_1");
//        }
        return R.success("修改状态成功");
    }


    //请求 URL: http://localhost:8080/dish?ids=1397850140982161409,1397849739276890114
    //请求方法: DELETE

    @DeleteMapping
    public R<String> delete(@RequestParam("ids") List<Long> ids) {
        dishService.deleteDish(ids);
        //删除不用清缓存  因为删除只有停售的  而停售的前台是查询不到的
        return R.success("删除成功");
    }

    //请求 URL: http://localhost:8080/dish/list?categoryId=1397844263642378242
    //请求方法: GET
//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish) {
//        //组装查询条件
//        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(Dish::getCategoryId, dish.getCategoryId())
//                .orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime)
//                .eq(Dish::getStatus, 1);
//        List<Dish> dishList = dishService.list(lambdaQueryWrapper);
//        return R.success(dishList);
//    }  redis 缓存菜品
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        //从redis中查询缓存的菜品数据
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //如果能从缓存中查询到 直接返回
        List<DishDto> dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtos != null) {
            return R.success(dishDtos);
        }
        //不能从缓存中查到则直接去数据库查询
        //组装查询条件
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dish::getCategoryId, dish.getCategoryId())
                .orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime)
                .eq(Dish::getStatus, 1);
        List<Dish> dishList = dishService.list(lambdaQueryWrapper);


        List<DishDto> dishDtoList = dishList.stream().map(d -> {
            DishDto dishDto = new DishDto();
            //copy dish数据到dishDto中
            BeanUtils.copyProperties(d, dishDto);
            Category category = categoryService.getById(d.getCategoryId());
            //将菜品分类名称保存
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            //查询菜品口味  用于前台显示
            Long dishId = d.getId();
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        //查询完成放入到redis中
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }
}
